/*
 * File     : StructureByReferenceStructureField.java
 * Created  : 20 Apr 2011
 * Revision : $Revision$
 *
 * Copyright © 2006-9 Matthew Wilson (mj. {my-surname} .uk {at} gmail.com)
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
package com.googlecode.dni.internal.structure;

import static com.googlecode.dni.internal.DniTypes.POINTER_TYPE;
import static com.googlecode.dni.internal.DniTypes.STRUCTURE_TYPE;
import static org.objectweb.asm.Opcodes.*;

import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;

import org.objectweb.asm.Label;
import org.objectweb.asm.MethodVisitor;
import org.objectweb.asm.Opcodes;

import com.googlecode.dni.internal.DniInternal;
import com.googlecode.dni.type.nativetype.NativeTypes;
import com.googlecode.dni.type.nativetype.SizeT;
import com.googlecode.dni.type.nativetype.Unsigned;
import com.googlecode.dni.type.structure.Structure;


/**
 * Encapsulates details of a {@link Structure} (by reference) structure's field
 * used during class generation.
 *
 * @author Matthew Wilson
 */
final class StructureByReferenceStructureField extends StructureField
{

    /** Primitive type for a pointer; assumes sizeof(size_t) == sizeof(void*) */
    private static final PrimitiveType POINTER = PrimitiveType.getType( SizeT.class );

    /** These annotations make no sense. */
    private static final List< Class< ? extends Annotation > > FORBIDDED_ANNOTATION_TYPES =
        new ArrayList< Class< ? extends Annotation > >();

    static
    {
        FORBIDDED_ANNOTATION_TYPES.add( Unsigned.class );
        FORBIDDED_ANNOTATION_TYPES.addAll( NATIVE_SIZED_TYPES );
    }

    private String structureImplName;

    private String structureFactoryImplName;


    /**
     * {@inheritDoc}
     */
    @Override
    void setGetter( final Method getter )
    {
        super.setGetter( getter );

        checkAnnotations( FORBIDDED_ANNOTATION_TYPES );

        Class< ? extends Structure > structureClass = getter.getReturnType().asSubclass( Structure.class );
        this.structureImplName = DniInternal.getStructureImplName( structureClass );
        this.structureFactoryImplName = DniInternal.getStructureFactoryImplName( structureClass );
    }

    @Override
    String getCType()
    {
        return "void*";
    }

    /**
     * {@inheritDoc}
     */
    @Override
    int getSize()
    {
        // size in the structure is that of a pointer
        return NativeTypes.POINTER_SIZE;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    void writeGetter( final MethodVisitor methodVisitor,
                      final String implName )
    {
        writeGetPointer( methodVisitor, implName );
        POINTER.writeGet( methodVisitor, true );
        methodVisitor.visitVarInsn( LSTORE, 1 );

        Label nonNull = new Label();
        methodVisitor.visitVarInsn( LLOAD, 1 );
        methodVisitor.visitInsn( LCONST_0 );
        methodVisitor.visitInsn( LCMP );
        methodVisitor.visitJumpInsn( IFNE, nonNull );

        methodVisitor.visitInsn( ACONST_NULL );
        methodVisitor.visitInsn( Opcodes.ARETURN );

        methodVisitor.visitLabel( nonNull );

        methodVisitor.visitFieldInsn( GETSTATIC,
                                      this.structureFactoryImplName,
                                      "INSTANCE",
                                      "L" + this.structureFactoryImplName + ";" );
        methodVisitor.visitVarInsn( LLOAD, 1 );
        methodVisitor.visitMethodInsn( INVOKEVIRTUAL,
                                       this.structureFactoryImplName,
                                       "fromPointer",
                                       "(J)L" + STRUCTURE_TYPE + ";" );

        methodVisitor.visitTypeInsn( CHECKCAST, this.structureImplName );

        methodVisitor.visitInsn( Opcodes.ARETURN );
    }

    /**
     * {@inheritDoc}
     */
    @Override
    void writeSetter( final MethodVisitor methodVisitor,
                      final String implName )
    {
        methodVisitor.visitVarInsn( ALOAD, 1 );

        Label nonNull = new Label();
        methodVisitor.visitInsn( ACONST_NULL );
        methodVisitor.visitJumpInsn( IF_ACMPNE, nonNull );

        writeGetPointer( methodVisitor, implName );
        methodVisitor.visitInsn( LCONST_0 );
        POINTER.writeSet( methodVisitor );

        methodVisitor.visitInsn( Opcodes.RETURN );

        methodVisitor.visitLabel( nonNull );
        writeGetPointer( methodVisitor, implName );
        methodVisitor.visitVarInsn( ALOAD, 1 );
        methodVisitor.visitMethodInsn( Opcodes.INVOKEINTERFACE,
                                       getFieldType().getName().replace( '.', '/' ),
                                       "pointer",
                                       "()L" + POINTER_TYPE + ";" );

        methodVisitor.visitMethodInsn( Opcodes.INVOKEVIRTUAL,
                                       POINTER_TYPE,
                                       "getAddress",
                                       "()J" );

        POINTER.writeSet( methodVisitor );

        methodVisitor.visitInsn( Opcodes.RETURN );
    }

    /**
     * {@inheritDoc}
     */
    @Override
    void postCreate()
    {
        super.postCreate();

        // ensure the field's structure type has been created
        if ( getFieldType() != getGetter().getDeclaringClass() )
        {
            DniInternal.getStructureRecord( getFieldType().asSubclass( Structure.class ) );
        }
    }

}
